package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.UpdateResult;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.*;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.service.TimeLineService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.SortOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service(version = "1.0.0")
@Slf4j
public class QuanZiApiImpl implements QuanZiApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Autowired
    private TimeLineService timeLineService;

    @Autowired
    private VideoApi videoApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    //用户是否点赞的前缀
    private static final String COMMENT_USER_LIEK_REDIS_KEY_PREFIX = "USER_LIKE_";

    //用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";

    /**
     * 查询好友动态
     *
     * @param userId   用户id
     * @param page     当前页数
     * @param pageSize 每一页查询的数据条数
     * @return
     */
    @Override
    public PageInfo<Publish> queryPublishList(Long userId, Integer page, Integer pageSize) {
        //分析: 查询好友的动态, 实际就是查询时间线表
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        // 查询时间线表, 根据发布时间倒叙排序查询
        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("date")));
        Query query = new Query().with(pageable);
        List<TimeLine> timeLines = mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);
        if (CollUtil.isEmpty(timeLines)) {
            //没有查询到数据
            return pageInfo;
        }

        //获取时间线列表中的发布id列表
        List<Object> ids = CollUtil.getFieldValues(timeLines, "publishId");

        // 根据获取到的动态id查询动态表, 动态发布时间倒叙排序查询
        Query queryPublish = Query.query(Criteria.where("id").in(ids)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishes = mongoTemplate.find(queryPublish, Publish.class);
        pageInfo.setRecords(publishes);
        return pageInfo;
    }

    /**
     * 发布动态
     *
     * @param publish
     * @return 发布成功返回动态id
     */
    @Override
    public String savePublish(Publish publish) {
        //校验Publish , 如果动态发布用户id和发布内容都为空, 则直接返回
        if (!ObjectUtil.isAllNotEmpty(publish.getText(), publish.getUserId())) {
            //发布失败
            return null;
        }

        //设置主键id
        publish.setId(ObjectId.get());

        try {
            // 设置自增长id(pid)
            publish.setPid(this.idService.createId(IdType.PUBLISH));
            publish.setCreated(System.currentTimeMillis());

            //写入到publish动态表中
            this.mongoTemplate.save(publish);

            //写入相册表
            Album album = new Album();
            album.setId(ObjectId.get());
            album.setCreated(System.currentTimeMillis());
            album.setPublishId(publish.getId());
            this.mongoTemplate.save(album, "quanzi_album_" + publish.getUserId());

            //写入好友的时间线表（异步写入）
            this.timeLineService.saveTimeLine(publish.getUserId(), publish.getId());
        } catch (Exception e) {
            //TODO 需要做事务的回滚，Mongodb的单节点服务，不支持事务，对于回滚我们暂时不实现了
            log.error("发布动态失败~ publish = " + publish, e);
        }

        return publish.getId().toHexString();
    }

    /**
     * 查询推荐动态
     *
     * @param userId   用户id
     * @param page     当前页数
     * @param pageSize 每一页查询的数据条数
     * @return
     */
    @Override
    public PageInfo<Publish> queryRecommendPublishList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        // 查询推荐结果数据
        String key = "QUANZI_PUBLISH_RECOMMEND_" + userId;
        String data = this.redisTemplate.opsForValue().get(key);
        if (StrUtil.isEmpty(data)) {
            return pageInfo;
        }

        //查询到的pid进行分页处理
        List<String> pids = StrUtil.split(data, ',');
        //计算分页
        //[0, 10]
        int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
        int startIndex = startEnd[0]; //开始
        int endIndex = Math.min(startEnd[1], pids.size()); //结束

        List<Long> pidLongList = new ArrayList<>();
        for (int i = startIndex; i < endIndex; i++) {
            pidLongList.add(Long.valueOf(pids.get(i)));
        }

        if (CollUtil.isEmpty(pidLongList)) {
            //没有查询到数据
            return pageInfo;
        }

        //根据pid查询publish
        Query query = Query.query(Criteria.where("pid").in(pidLongList))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(query, Publish.class);
        if (CollUtil.isEmpty(publishList)) {
            //没有查询到数据
            return pageInfo;
        }

        pageInfo.setRecords(publishList);
        return pageInfo;
    }

    /**
     * 根据id查询动态
     *
     * @param id 动态id
     * @return
     */
    @Override
    public Publish queryPublishById(String id) {
        return mongoTemplate.findById(new ObjectId(id), Publish.class);
    }

    /**
     * 点赞功能
     *
     * @param userId  登录用户id
     * @param publishId  发布动态id
     * @return
     */
    @Override
    public Boolean likeComment(Long userId, String publishId) {
        //判断用户是否已经点赞, 如果已经点赞则直接返回即可
        if (queryUserIsLike(userId, publishId)) {
            return false;
        }

        //如没有点赞, 则保存点赞数据
        Boolean result = saveComment(userId, publishId, CommentType.LIKE, null);
        //判断是否保存成功, 如果保存失败则直接返回即
        if (!result) {
            return false;
        }

        //如果保存成功, 则修改redis中的点赞数以及是否点赞
        //修改点赞数
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hasKey = CommentType.LIKE.toString();
        redisTemplate.opsForHash().increment(redisKey,hasKey,1);

        //用户是否点赞
        String userHashKey = getCommentUserLikeRedisKeyPrefix(userId);
        redisTemplate.opsForHash().put(redisKey,userHashKey,"1");

        return true;
    }

    /**
     *保存评论数据
     *
     * @param userId  登录用户id
     * @param publishId  发布动态id
     * @param commentType  评论类型
     * @param content  评论内容
     * @return
     */
    private Boolean saveComment(Long userId, String publishId, CommentType commentType, String content) {
        try {
            Comment comment = new Comment();
            comment.setId(ObjectId.get());
            comment.setUserId(userId);
            comment.setPublishId(new ObjectId(publishId));
            // 评论类型
            comment.setCommentType(commentType.getType());
            // 内容
            comment.setContent(content);
            comment.setCreated(System.currentTimeMillis());

            Publish publish = queryPublishById(publishId);
            if (ObjectUtil.isNotEmpty(publish)){
                comment.setPublishUserId(publish.getUserId());
            }else {
                //查询评论
                Comment myComment = queryCommentById(publishId);
                if (ObjectUtil.isNotEmpty(myComment)){
                    comment.setPublishUserId(myComment.getUserId());
                }else {
                    Video video = videoApi.queryVideoById(publishId);
                    if (ObjectUtil.isNotEmpty(video)){
                        comment.setPublishUserId(video.getUserId());
                    }else {
                        //TODO 其他情况, 直接返回
                        return false;
                    }
                }
            }
            mongoTemplate.save(comment);
            return true;
        } catch (Exception e) {
            log.error("保存Comment出错~ userId = " + userId + ", publishId = " + publishId + ", commentType = " + commentType, e);
        }
        return false;
    }

    /**
     * 根据ipublishId查询Comment对象
     *
     * @param publishId  发布动态id
     * @return
     */
    private Comment queryCommentById(String publishId) {
        return mongoTemplate.findById(new ObjectId(publishId),Comment.class);
    }

    /**
     * 获取评论redisKey
     *
     * @param publishId  发布动态id
     * @return
     */
    private String getCommentRedisKeyPrefix(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    /**
     * 获取点赞hashKey前缀
     *
     * @param userId  登录用户id
     * @return
     */
    private String getCommentUserLikeRedisKeyPrefix(Long userId) {
        return COMMENT_USER_LIEK_REDIS_KEY_PREFIX + userId;
    }

    /**
     * 取消点赞功能
     *
     * @param userId  登录用户id
     * @param publishId  发布动态id
     * @return
     */
    @Override
    public Boolean disLikeComment(Long userId, String publishId) {
        //判断用户是否已经点赞, 如果没有点赞则直接返回即可
        if (!queryUserIsLike(userId, publishId)) {
            return false;
        }

        //如果已经点赞, 则删除点赞数据
        Boolean result = removeComment(userId,publishId,CommentType.LIKE);
        //如果删除失败, 则直接返回
        if (!result){
            return false;
        }

        //如果删除成功, 则修改redis中的数据
        //修改点赞数
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        redisTemplate.opsForHash().increment(redisKey,hashKey,-1);

        //用户是否点赞
        String userHashKey = getCommentUserLikeRedisKeyPrefix(userId);
        redisTemplate.opsForHash().delete(redisKey, userHashKey);
        return true;
    }

    /**
     * 删除点赞数据
     * @param userId  登录用户id
     * @param publishId  发布动态id
     * @param commentType  评论类型
     * @return
     */
    private Boolean removeComment(Long userId, String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("userId").is(userId)
        .and("publishId").is(new ObjectId(publishId))
        .and("commentType").is(commentType.getType()));
        return mongoTemplate.remove(query,Comment.class).getDeletedCount() > 0 ;
    }

    /**
     * 查询点赞数
     *
     * @param publishId  发布动态id
     * @return
     */
    @Override
    public Long queryLikeCount(String publishId) {
        //从redis中命中查询, 如果命中则直接返回即可
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        Object data = redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(data)){
            return Convert.toLong(data);
        }

        //如果没有命中, 则查询MongnDB
        Long count = queryCommentCount(publishId,CommentType.LIKE);
        //将查询结果存储到redis中
        redisTemplate.opsForHash().put(redisKey,hashKey,String.valueOf(count));
        return count;
    }

    /**
     * 查询MongnDB中点赞数据
     *
     * @param publishId 发布动态id
     * @param commentType  评论类型
     * @return
     */
    private Long queryCommentCount(String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
        .and("commentType").is(commentType.getType()));
        return mongoTemplate.count(query,Comment.class);
    }

    /**
     * 查询用户是否点赞该动态
     *
     * @param userId  登录用户id
     * @param publishId  发布动态id
     * @return
     */
    @Override
    public Boolean queryUserIsLike(Long userId, String publishId) {
        //从redis中查询数据
        String userHashKey = getCommentUserLikeRedisKeyPrefix(userId);
        String redisKey = getCommentRedisKeyPrefix(publishId);
        Object data = redisTemplate.opsForHash().get(redisKey, userHashKey);
        if (ObjectUtil.isNotEmpty(data)){
            return StrUtil.equals(Convert.toStr(data),"1");
        }

        //查询MongoDB数据, 是否已经点赞
        Query query = Query.query(Criteria.where("userId").is(userId)
        .and("commentType").is(CommentType.LIKE));
        long count = mongoTemplate.count(query, Comment.class);
        //如果查询数据为0, 则直接返回
        if (count == 0){
            return false;
        }

        //写入到redis中
        redisTemplate.opsForHash().put(redisKey,userHashKey,"1");
        return true;
    }

    /**
     * 喜欢
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean loveComment(Long userId, String publishId) {
        //判断用户是否已经喜欢, 如果是true直接返回
        if (queryUserIsLove(userId,publishId)){
            return false;
        }

        //如果没有, 则保存喜欢数据
        Boolean result = saveComment(userId, publishId, CommentType.LOVE, null);
        if (!result){
            return false;
        }

        //保存成功后, 修改redis中的总喜欢书
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        redisTemplate.opsForHash().increment(redisKey,hashKey,1);

        //标记用户已经喜欢
        hashKey = getCommentUserLoveRedisKey(userId);
        redisTemplate.opsForHash().put(redisKey,hashKey,"1");
        return true;
    }

    /**
     * 获取喜欢redisKey
     *
     * @param userId
     * @return
     */
    private String getCommentUserLoveRedisKey(Long userId) {
        return COMMENT_USER_LOVE_REDIS_KEY_PREFIX + userId;
    }

    /**
     * 取消喜欢
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean disLoveComment(Long userId, String publishId) {
        if (!queryUserIsLove(userId,publishId)){
            //如果用户没有喜欢, 则直接返回
            return false;
        }

        //删除喜欢数据
        Boolean result = removeComment(userId, publishId, CommentType.LOVE);
        if (!result){
            //删除失败
            return false;
        }

        //删除redis中的数据
        //修改喜欢数
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        redisTemplate.opsForHash().increment(redisKey,hashKey,-1);

        //用户是否喜欢

        String userHashKey = getCommentUserLoveRedisKey(userId);
        redisTemplate.opsForHash().delete(redisKey, userHashKey);
        return true;
    }

    /**
     * 查询喜欢数
     *
     * @param publishId
     * @return
     */
    @Override
    public Long queryLoveCount(String publishId) {
        //从redis中命中查询, 如果命中则直接返回即可
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        Object data = redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(data)){
            return Convert.toLong(data);
        }

        //如果没有命中, 则查询MongnDB
        Long count = queryCommentCount(publishId, CommentType.LOVE);

        //将查询结果存储到redis中
        redisTemplate.opsForHash().put(redisKey,hashKey,String.valueOf(count));
        return count;
    }

    /**
     * 查询用户是否喜欢该动态
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean queryUserIsLove(Long userId, String publishId) {
        //从redis中查询数据
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = this.getCommentUserLoveRedisKey(userId);
        Object data = redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(data)){
            return StrUtil.equals(Convert.toStr(data),"1");
        }

        //查询MongoDB数据, 是否已经喜欢
        Query query = Query.query(Criteria.where(publishId).is(new ObjectId(publishId))
                                    .and("userId").is(userId)
                                    .and("commentType").is(CommentType.LOVE.getType()));
        long count = mongoTemplate.count(query, Comment.class);
        if (count == 0){
            return false;
        }

        //标记用户已经喜欢
        redisTemplate.opsForHash().put(redisKey,hashKey,"1");

        return true;
    }

    /**
     * 查询评论
     *
     * @param publishId  发布动态id
     * @param page  页数
     * @param pageSize  条数
     * @return
     */
    @Override
    public PageInfo<Comment> queryCommentList(String publishId, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.asc("created")));
        //查询评论列表
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                        .and("commentType").is(CommentType.COMMENT.getType())).with(pageRequest);
        List<Comment> commentsList = mongoTemplate.find(query, Comment.class);
        PageInfo<Comment> pageInfo = new PageInfo();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(commentsList);
        return pageInfo;
    }

    /**
     * 发表评论
     *
     * @param userId  登录ID
     * @param publishId  发布动态id
     * @param content  评论内容
     * @return
     */
    @Override
    public Boolean saveComment(Long userId, String publishId, String content) {
        return saveComment(userId, publishId, CommentType.COMMENT, content);
    }

    /**
     * 查询评论数
     *
     * @param publishId
     * @return
     */
    @Override
    public Long queryCommentCount(String publishId) {
        return queryCommentCount(publishId,CommentType.COMMENT);
    }

    /**
     * 查询对我的点赞消息列表
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Comment> queryLikeCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return queryCommentListByUser(userId, CommentType.LIKE,page,pageSize);
    }

    /**
     * 查询对我的喜欢消息列表
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Comment> queryLoveCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return queryCommentListByUser(userId, CommentType.LOVE,page,pageSize);
    }

    /**
     * 查询对我的评论消息
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Comment> queryCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return queryCommentListByUser(userId, CommentType.COMMENT,page,pageSize);
    }

    /**
     * 查询相册表
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Publish> queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        PageRequest pageRequest = PageRequest.of(page - 1 , pageSize , Sort.by(Sort.Order.desc("created")));
        Query query  = new Query().with(pageRequest);

        // 查询自己的相册表
        List<Album> albumList = mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);
        if (CollUtil.isEmpty(albumList)){
            return pageInfo;
        }
        List<Object> publishIdList = CollUtil.getFieldValues(albumList, "publishId");
        Query queryPublish = Query.query(Criteria.where("id").in(publishIdList)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = mongoTemplate.find(queryPublish, Publish.class);
        pageInfo.setRecords(publishList);
        return pageInfo;
    }

    private PageInfo<Comment> queryCommentListByUser(Long userId, CommentType commentType, Integer page, Integer pageSize) {
        // 手动设置分页, 按照发布时间倒序排序
        PageRequest pageRequest = PageRequest.of(page - 1 , pageSize ,Sort.by(Sort.Order.desc("created")));

        // 根据发布id和评论类型为条件, 在数据库中查询数据
        Query query = Query.query(Criteria.where("publishUserId").is(userId).and("commentType").is(commentType.getType())).with(pageRequest);
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);

        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(commentList);
        return pageInfo;
    }


    //    ============
    /**
     * 自己动态总条数
     *
     * @param uid
     * @return
     */
    @Override
    public Long queryUserPublishCount(String uid , String state,String id) {
        //判断uid是否为空, 为空查自己的的动态, 不为空查审核消息
        //不为空的查固定uid的动态
        if (uid != null && !(uid.equals(""))) {
            Long userId = Long.valueOf(uid);
            Query query = new Query();
            long count = mongoTemplate.count(query, Album.class, "quanzi_album_" + userId);
            return count;
            //查所有的时候,判断状态（3，4，5）的时候查询publish表中的字段值
        } else {
//这里id(userId)不为空, 要传进来,根据id和state计数
            long count1=0;
            if(ObjectUtil.isNotEmpty(id)){
//                这里要根据id(userId)和状态(state)两个字段查publish表
                Query query = new Query();
                if (state.equals("all")) {

                    query =Query.query(Criteria.where("userId").is(Convert.toLong(id)));
                    count1 = mongoTemplate.count(query, Publish.class);
                } else if (state.equals("3")) {
                    query =Query.query(Criteria.where("userId").is(Convert.toLong(id))
                                                    .andOperator(Criteria.where("state").in("1","3")));
//                    Query query = Query.query(Criteria.where("state").in("1","3"));
                    count1 = mongoTemplate.count(query, Publish.class);
                } else if (state.equals("4")) {
                    query =Query.query(Criteria.where("userId").is(Convert.toLong(id))
                            .andOperator(Criteria.where("state").in("2","5")));
                    count1 = mongoTemplate.count(query, Publish.class);
                } else{
                    query =Query.query(Criteria.where("userId").is(Convert.toLong(id))
                            .andOperator(Criteria.where("state").in("4","6")));
                    count1 = mongoTemplate.count(query, Publish.class);
                }
            }else{
//                id为空.,判断状态
                if (state.equals("all")) {
                    Query query = new Query();
                    count1 = mongoTemplate.count(query, Publish.class);
                } else if (state.equals("3")) {
                    Query query = Query.query(Criteria.where("state").in("1","3"));
                    count1 = mongoTemplate.count(query, Publish.class);
                } else if (state.equals("4")) {
                    Query query = Query.query(Criteria.where("state").in("2","5"));
                    count1 = mongoTemplate.count(query, Publish.class);
                } else{
                    Query query = Query.query(Criteria.where("state").in("4","6"));
                    count1 = mongoTemplate.count(query, Publish.class);
                }
            }
//            ==============
//            long count = 0;
//            if (state.equals("all")) {
//                Query query = new Query();
//                count = mongoTemplate.count(query, Publish.class);
//            } else if (state.equals("3")) {
//                Query query = Query.query(Criteria.where("state").in("1","3"));
//                count = mongoTemplate.count(query, Publish.class);
//            } else if (state.equals("4")) {
//                Query query = Query.query(Criteria.where("state").in("2","5"));
//                count = mongoTemplate.count(query, Publish.class);
//            } else{
//                Query query = Query.query(Criteria.where("state").in("4","6"));
//                count = mongoTemplate.count(query, Publish.class);
//            }



            return count1;
        }

    }
    // 查所有数据
    @Override
    public List<Publish> queryUserPublish(Integer pagesize, Integer page, String sortProp, String sortOrder, String id, String sd, String ed, String uid, String state) {
//          判断排序的字段是什么
//        如果uid为空的情况下就是根据创建时间字段查询所有
        Sort orders = null;
        if ("createDate".equals(sortProp)) {
            sortProp = "created";
        }
//          判断排序方式
        if (sortOrder.equals("ascending")) {
            orders = Sort.by(Sort.Order.asc(sortProp));
        } else {
            orders = Sort.by(Sort.Order.desc(sortProp));
        }

        //判断uid是否为空, 为空查主页面所有的动态, 不为空查个人信息和动态等信息
//        为空的话就查询
        if (uid != null && !(uid.equals(""))) {
            Long userId=Long.valueOf(uid);
            SortOperation count = null;
//            如果是喜欢数排序
            if (sortProp.equals("likeCount")){
                if (sortOrder.equals("ascending")) {
                    count = Aggregation.sort(Sort.Direction.ASC, "count");
                } else {
                    count = Aggregation.sort(Sort.Direction.DESC, "count");
                }
            Query query = Query.query(Criteria.where("userId").is(userId));
//            查询所有动态，收集动态id
            List<Publish> publishes = mongoTemplate.find(query, Publish.class);
            Set<ObjectId> publisheIds=publishes.stream().map(Publish::getId).collect(Collectors.toSet());
//            开始进行分页查询
            Aggregation aggregation = Aggregation.newAggregation(
//                    相似
                    Aggregation.match(Criteria.where("commentType").is(Integer.valueOf(1))),
                    Aggregation.match(Criteria.where("publishId").in(publisheIds)),
                    Aggregation.group("publishId").count().as("count"),
                    count
            );
//            因为这个是根据点赞数查询，所以获取点赞的数据来进行排序,根据点赞的多少来排序，得到一个具有顺序的list的集合
            List<Map> list = mongoTemplate.aggregate(aggregation, Comment.class, Map.class).getMappedResults();
//            创建集合来获取所有的id集合
            ArrayList<ObjectId> pid = new ArrayList<>();
            for (Map map : list) {
                pid.add(new ObjectId(map.get("_id").toString()));
            }
            if (sortOrder.equals("ascending")){
//                升序排序查询动态，要添加没有点赞的id
                for (ObjectId publisheId : publisheIds) {
                    if (!pid.contains(publisheId)) {
                        pid.add(0,publisheId);
                    }
                }
            }else {
//               降序情况下
                //收集点赞之外的id
                for (ObjectId publisheId : publisheIds) {
                    if (!pid.contains(publisheId)) {
                        pid.add(publisheId);
                    }
                }
            }
//            根据集合来查所有的动态详情
            ArrayList<Publish> publishesPageList = new ArrayList<>();
            ArrayList<Publish> publishesList = new ArrayList<>();
            for (ObjectId objectId : pid) {
                Publish publish = mongoTemplate.findById(objectId, Publish.class);
                publishesList.add(publish);
            }
//            分页
            int startIndex=(page-1)*pagesize;
//            当最后剩下的数据不足页数的时候就
            if (startIndex<publishesList.size()){
                int endIndex = startIndex + pagesize;
                if (endIndex >= publishesList.size()) {
                    endIndex = publishesList.size();
                }

                for (int i = startIndex; i < endIndex; i++) {
                    publishesPageList.add(publishesList.get(i));
                }
            }
//            将封装好的按照点赞数排序的数据返回
            return publishesPageList;
            }
//            不是根据点赞数来查询直接找相册表来查询对应顺序的相册表
            PageRequest pageRequest = PageRequest.of(page - 1, pagesize, orders);
            Query query = new Query().with(pageRequest);
            List<Album> albumList = this.mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);

//            为空则表示没有数据
            if (CollectionUtils.isEmpty(albumList)) {
                return null;
            }

            List<ObjectId> publishIds = new ArrayList<>();
            for (Album album : albumList) {
                publishIds.add(album.getPublishId());
            }

            //查询发布信息,根据相同的uid来查询共同的消息,返回消息给前台
            Query queryPublish = Query.query(Criteria.where("id").in(publishIds)).with(orders);
            List<Publish> publishList = this.mongoTemplate.find(queryPublish, Publish.class);

            return publishList;

        }else{
//            在这里查询所有
            PageRequest pageRequest = PageRequest.of(page - 1, pagesize, orders);
            Criteria criteria1 = new Criteria();
            Criteria criteria2 = new Criteria();
            Criteria criteria3 = new Criteria();
            Criteria criteria = new Criteria();
            //如果动态id不为空, 加入条件
//            就是现在根据动态id(这里的动态相当于我传的用户id但是在前端是id字段)来查一个指定的动态
            if (id!=null&&StrUtil.isNotEmpty(id)){
                criteria1=Criteria.where("userId").is(Long.valueOf(id));/*_id是动态id,userId*/
            }
//            如果时间不为空的时候，需要解析时间获取毫秒值，然后加入条件中
            if (sd!=null&& ed!=null&&!(sd.equals("-1"))&&!(ed.equals("-1"))){
/*                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//               解析时间
                try {
                    Date parse = format.parse(sd);
                    Date parse1 = format.parse(ed);
//                    获取毫秒值，加入条件
                    criteria2=Criteria.where("created").gte(parse.getTime()).lte(parse1.getTime());*/

//===========
//                传入的就是long类型
                try{
                criteria2=Criteria.where("created").gte(Long.valueOf(sd)).lte(Long.valueOf(ed));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
//      如果状态不为空
            if (state!=null){
                List<String> list=new ArrayList<>();
                if (state.equals("all")) {
                    list.add("1");
                    list.add("2");
                    list.add("3");
                    list.add("4");
                    list.add("5");
                    list.add("6");
                    criteria3 = Criteria.where("state").in(list);
                } else if (state.equals("3")) {
                    list.add("1");
                    list.add("3");
                    criteria3 = Criteria.where("state").in(list);
                } else if (state.equals("4")) {
                    list.add("2");
                    list.add("5");
                    criteria3 = Criteria.where("state").in(list);
                } else{
                    list.add("4");
                    list.add("6");
                    criteria3 = Criteria.where("state").in(list);
                }
            }
            ArrayList<String> strings = new ArrayList<>();
            strings.add("1");
            strings.add("3");
            Query query2 = Query.query(criteria.in(strings)).with(pageRequest);
//            最后不管别的条件是不是空，都查询所有
            criteria=criteria.andOperator(criteria1,criteria2,criteria3);
            Query query1 = Query.query(criteria).with(pageRequest);
            Query query = new Query().with(pageRequest);
            List<Publish> publishList= mongoTemplate.find(query1,Publish.class);
            return publishList;
        }
    }

    /**
     * 置顶
     * +++++++
     * 1是没有置顶
     * 2是置顶
     * @param id
     * @return
     */
    @Override
    public Boolean top(String id) {
        Query query1 = Query.query(Criteria.where("id").is(new ObjectId(id)).and("topState").is(2));
        Publish publish = mongoTemplate.findOne(query1, Publish.class);
        if (publish != null) {
            return false;
        }
        //更新条件
        Query query = Query.query(Criteria.where("id").is(new ObjectId(id)));
        Update topState = Update.update("topState", 2);
        UpdateResult updateResult = mongoTemplate.updateFirst(query, topState, Publish.class);
        return updateResult.getMatchedCount() > 0;
    }

    /**
     * 取消置顶
     * @param id
     * @return
     */
    @Override
    public Boolean unTop(String id) {
        //更新条件
        Query query = Query.query(Criteria.where("id").is(new ObjectId(id)));
        Update topState = Update.update("topState", 1);
        UpdateResult updateResult = mongoTemplate.updateFirst(query, topState, Publish.class);
        return updateResult.getMatchedCount() > 0;
    }
/*通过状态字段改为*/
/*
 * 通过状态字段改为
 *
 * */
@Override
public Boolean messagePass(String[] ids) {
    try {
        for (String id : ids) {
            //查询需要通过的publish数据
            Query query = Query.query(Criteria.where("id").is(id));
            Publish publish = this.mongoTemplate.findOne(query, Publish.class);
            System.out.println(publish);
            if (ObjectUtil.isEmpty(publish)) {
                return false;
            }

            //判断是否已经通过过了,防止重复操作
            Integer state = Convert.toInt(publish.getState());
            if (state == 2 || state == 5) {
                continue;
            }

            //更新数据库信息,修改为已通过
            Query updateQuery = Query.query(Criteria.where("id").is(id));
            Update update = Update.update("state", "5");  //2为自动审核通过、5为人工审核通过
            this.mongoTemplate.updateFirst(updateQuery, update, Publish.class);
        }

        return true;
    } catch (Exception e) {
        log.error("消息拒绝出错,ids="+ids,e);
    }
    return false;

}


    /*拒绝*/
    @Override
    public Boolean messageReject(String[] ids) {
        try {
            for (String id : ids) {
                //查询需要拒绝的publish数据
                Query query = Query.query(Criteria.where("id").is(id));
                Publish publish = this.mongoTemplate.findOne(query, Publish.class);
                System.out.println(publish);
                if (ObjectUtil.isEmpty(publish)) {
                    return false;
                }

                //判断是否已经拒绝过了,防止重复操作
                Integer state = Convert.toInt(publish.getState());
                if (state == 4 || state == 6) {
                    continue;
                }

                //更新数据库信息,修改为已拒绝
                Query updateQuery = Query.query(Criteria.where("id").is(id));
                Update update = Update.update("state", "4");   //4为人工审核拒绝、6为自动审核拒绝
                this.mongoTemplate.updateFirst(updateQuery, update, Publish.class);
            }

            return true;
        } catch (Exception e) {
            log.error("消息拒绝出错,ids="+ids,e);
        }
        return false;
    }

    /*撤销*/
    @Override
    public Boolean messageRevocation(String[] ids) {

        try {
            for (String id : ids) {
                //查询需要撤销的publish数据
                Query query = Query.query(Criteria.where("id").is(id));
                Publish publish = this.mongoTemplate.findOne(query, Publish.class);
                System.out.println(publish);
                if (ObjectUtil.isEmpty(publish)) {
                    return false;
                }

                //判断是否为待审核,防止重复操作
                Integer state = Convert.toInt(publish.getState());
                if (state == 1 || state == 3) {
                    continue;
                }

                //更新数据库信息,修改为待审核
                Query updateQuery = Query.query(Criteria.where("id").is(id));
                Update update = Update.update("state", "3");   //1为待审核、3为待人工审核，
                this.mongoTemplate.updateFirst(updateQuery, update, Publish.class);
            }

            return true;
        } catch (Exception e) {
            log.error("消息撤销出错,ids="+ids,e);
        }
        return false;
    }

    /**
     * 待审核  1   3
     * @return
     */
    @Override
    public Long queryStateWait(String id,Long sd,Long ed) {
        Query query1 ;
//        这里是id的判断(userId(1)),这个时候uid为null,状态自己判断的
//        criteria2=Criteria.where("created").gte(Long.valueOf(sd)).lte(Long.valueOf(ed));
/*        if (StrUtil.isNotEmpty(id)){
      query1 = Query.query(Criteria.where("state").in("1", "3")
                                        .and("userId").is(Convert.toLong(id)));
        }else {
            query1 = Query.query(Criteria.where("state").in("1", "3"));
        }*/
//=========
/*        if (ObjectUtil.isAllNotEmpty(sd,ed)){
            Criteria criteria2 = new Criteria();
            Criteria criteria3 = new Criteria();
            criteria2=Criteria.where("created").gte(Long.valueOf(sd)).lte(Long.valueOf(ed));
*//*            criteria3=
                    query1 = Query.query(Criteria.where("state").in("1", "3")
                            .and("userId").is(Convert.toLong(id))
                            .andOperator(Criteria.where("created").gte(Long.valueOf(sd)).lte(Long.valueOf(ed))));*//*
        }*/
//        ===================
        if (ObjectUtil.isAllNotEmpty(id,sd,ed)&&sd>0&&ed>0){
            query1 = Query.query(Criteria.where("state").in("1", "3")
                    .and("userId").is(Convert.toLong(id))
                    .andOperator(Criteria.where("created").gte(Long.valueOf(sd)).lte(Long.valueOf(ed))));
//            这里就是id不为空,,sd,ed可能为空
        }else if (ObjectUtil.isNotEmpty(id)){
            query1 = Query.query(Criteria.where("state").in("1", "3")
                    .and("userId").is(Convert.toLong(id)));
        }else if (ObjectUtil.isAllNotEmpty(ed,sd)&&sd>0&&ed>0){
            query1 = Query.query(Criteria.where("state").in("1", "3")
                    .andOperator(Criteria.where("created").gte(Long.valueOf(sd)).lte(Long.valueOf(ed))));
        }else {
//            mei id,time<0
            query1 = Query.query(Criteria.where("state").in("1", "3"));
        }

        return mongoTemplate.count(query1,Publish.class);
    }
    /**
     * 通过 2 5
     * @return
     */
    @Override
    public Long queryStatePass(String id,Long sd,Long ed) {
        Query query1 ;
        if (ObjectUtil.isAllNotEmpty(id,sd,ed)&&sd>0&&ed>0){
            query1 = Query.query(Criteria.where("state").in("2", "5")
                    .and("userId").is(Convert.toLong(id))
                    .andOperator(Criteria.where("created").gte(Long.valueOf(sd)).lte(Long.valueOf(ed))));
//            这里就是id不为空,,sd,ed可能为空
        }else if (ObjectUtil.isNotEmpty(id)){
            query1 = Query.query(Criteria.where("state").in("2", "5")
                    .and("userId").is(Convert.toLong(id)));
        }else if (ObjectUtil.isAllNotEmpty(ed,sd)&&sd>0&&ed>0){
            query1 = Query.query(Criteria.where("state").in("2", "5")
                    .andOperator(Criteria.where("created").gte(Long.valueOf(sd)).lte(Long.valueOf(ed))));
        }else {
            query1 = Query.query(Criteria.where("state").in("2", "5"));
        }
        return mongoTemplate.count(query1,Publish.class);
    }
    /**
     * 拒绝 4 6
     * @return
     */
    @Override
    public Long queryStateNoPass(String id,Long sd,Long ed) {
        Query query1 ;
        if (ObjectUtil.isAllNotEmpty(id,sd,ed)&&sd>0&&ed>0){
            query1 = Query.query(Criteria.where("state").in("4", "6")
                    .and("userId").is(Convert.toLong(id))
                    .andOperator(Criteria.where("created").gte(Long.valueOf(sd)).lte(Long.valueOf(ed))));
//            这里就是id不为空,,sd,ed可能为空
        }else if (ObjectUtil.isNotEmpty(id)){
            query1 = Query.query(Criteria.where("state").in("4", "6")
                    .and("userId").is(Convert.toLong(id)));
        }else if (ObjectUtil.isAllNotEmpty(ed,sd)&&sd>0&&ed>0){
            query1 = Query.query(Criteria.where("state").in("4", "6")
                    .andOperator(Criteria.where("created").gte(Long.valueOf(sd)).lte(Long.valueOf(ed))));
        }else {
            query1 = Query.query(Criteria.where("state").in("4", "6"));
        }
        return mongoTemplate.count(query1,Publish.class);
    }

    @Override
    public List<Comment> queryCommentsByPublishId(String pagesize, String page, String sortProp, String sortOrder, String messageID) {
        Sort type=null;
        sortProp="created";

        //排序方式
        if (sortOrder.equals("descending")){
            type=Sort.by(Sort.Order.desc(sortProp));//倒序
        }else {
            type=Sort.by(Sort.Order.asc(sortProp));//正序
        }

        Pageable pageable=PageRequest.of(
                Integer.parseInt(page)-1,
                Integer.parseInt(pagesize),
                type);
        Query query=Query.query(Criteria.where("publishId").is(new ObjectId(messageID)).and("commentType").is(2)).with(pageable);
        List<Comment> comments=mongoTemplate.find(query,Comment.class);
        return comments;
    }

    /**
     * 根据动态id,评论类型,判断该评论类型的个数
     *
     * @param publishId
     * @param type
     * @return
     */
    @Override
    public Long queryCommentCount(String publishId, Integer type) {
        Query query=Query.query(Criteria.where("publishId").is(new ObjectId(publishId)).and("commentType").is(type));
        return mongoTemplate.count(query,Comment.class);
    }
}